#!/bin/sh
#
#descipt: this script start the ipvsadm and monitor the realserver backend

#defined ip and port array
rtmp_servers=(192.168.13.99:1935 192.168.13.100:1935)
web_server=(192.168.13.99:80  192.168.13.100:80)
yum_server=(192.168.13.99:8888  192.168.13.100:8888)
virtual_server=(118.145.8.98:1935  118.145.8.98:80 118.145.8.98:8888)
DIP='118.145.8.98'

function is_open() {
	tmpvar=$1[@]
	rtmp_server=("${!tmpvar}")
        for var in "${rtmp_server[@]}";
        do
                server_ip=$(echo $var | awk -F ':' '{print $1}')
                server_port=$(echo $var | awk -F ':' '{print $2}')
                port_status=$(nmap -p $server_port $server_ip | grep $server_port | awk {'print $2'})
		record_count=$(ipvsadm -Ln | grep $server_ip:$server_port|wc -l)

		case $port_status in
		     open)
			       if [ $record_count -eq 0 ]
       		               then
                               		ipvsadm -a -t $DIP:$server_port -r $server_ip:$server_port -g
	                       fi
			       ;;
			*)
			       if [ $record_count -ne 0 ]
                               then
				        ipvsadm -d -t $DIP:$server_port -r $server_ip:$server_port
			       fi
		esac
        done
}


#Flush ipvs table
ipvsadm -C

for directory in ${virtual_server[@]}
do
	dserver_ip=$(echo $directory | awk -F ':' '{print $1}')
	dserver_port=$(echo $directory | awk -F ':' '{print $2}')
	ipvsadm -A -t $dserver_ip:$dserver_port -s rr
done

which nmap > /dev/null 2>&1
if [ $? -eq 0 ]
then
	while :
	do
		is_open rtmp_servers
		is_open web_server
		is_open yum_server
	done
	sleep 5
fi
